package com.kehao.leetcode.jzoffer;

import org.junit.Test;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/6/23 16:41
 */
public class JZSolution025 {

    private static class ListNode {
        int val;
        ListNode next;
        ListNode() {
        }
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    private ListNode reverseList(ListNode head) {
        if(head==null) return null;
        ListNode h = new ListNode();
        ListNode p = head;
        ListNode p1 = p.next;
        while (p!=null){
            p.next = h.next;
            h.next = p;
            p = p1;
            p1 = p1==null?p1:p1.next;
        }
        return h.next;
    }


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode h = new ListNode();
        l1 = reverseList(l1);
        l2 = reverseList(l2);
        int another = 0;
        while (l1!=null&&l2!=null){
            int sum = l1.val+l2.val+another;
            if(sum>9){
                another = sum/10;
                sum = sum%10;
            }else {
                another = 0;
            }
            ListNode p = new ListNode(sum);
            p.next = h.next;
            h.next = p;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1!=null){
            int sum = l1.val+another;
            if(sum>9){
                another = sum/10;
                sum = sum%10;
            }else {
                another = 0;
            }
            ListNode p = new ListNode(sum);
            p.next = h.next;
            h.next = p;
            l1 = l1.next;
        }

        while (l2!=null){
            int sum = l2.val+another;
            if(sum>9){
                another = sum/10;
                sum = sum%10;
            }else {
                another = 0;
            }
            ListNode p = new ListNode(sum);
            p.next = h.next;
            h.next = p;
            l2 = l2.next;
        }
        if(another!=0){
            ListNode p = new ListNode(another);
            p.next = h.next;
            h.next = p;
        }

        return h.next;
    }

    @Test
    public void test01(){
        ListNode listNode = addTwoNumbers(new ListNode(5), new ListNode(5));
        System.out.println();
    }


}
